package com.xianan.xuhui.netsecurityproject.utils;

import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

/**
 * 国际化资源工具类
 */
@Component
public class I18nUtil {
    private static MessageSource messageSource;

    public I18nUtil(MessageSource messageSource) {
        I18nUtil.messageSource = messageSource;
    }

    public static String get(String key) {
        String msg = "";
        try {
            msg = messageSource.getMessage(key, null, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            msg = key;
        }
        return msg;
    }

    /**
     * 一个参数
     * @param key
     * @param arg0
     * @return
     */
    public static String get(String key, Object arg0) {
        String msg = "";
        try {
            msg =  messageSource.getMessage(key, new Object[]{arg0}, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            msg = key;
        }
        return msg;
    }
    //两个参数
    public static String get(String key, Object arg0,Object arg1) {
        String msg = "";
        try {
            msg =  messageSource.getMessage(key, new Object[]{arg0,arg1}, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            msg = key;
        }
        return msg;
    }
    //三个参数
    public static String get(String key, Object arg0,Object arg1,Object arg2) {
        String msg = "";
        try {
            msg =  messageSource.getMessage(key, new Object[]{arg0,arg1,arg2}, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            msg = key;
        }
        return msg;
    }
    //任意个参数
    public static String get(String key, Object[] args) {
        String msg = "";
        try {
            msg =  messageSource.getMessage(key, args, LocaleContextHolder.getLocale());
        }catch (NoSuchMessageException e){
            msg = key;
        }
        return msg;
    }
}
